#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "constants.h"
#include "model.h"

#define is_digit(c) (c>='0' && c<='9')
#define is_literal(c) ((c>='a' && c<='z') || (c>='A' && c<='Z'))
#define is_not_special_character(c) (c=='_' || c=='.')



char token[64];
FILE *archivo;
int cont=0;

int  init(char *arch);
char* get_token();
int is_id();
int body_open();
int body_close();
int property();
int instruction();
int body();
int begin_parse();

int  init(char *arch)
{
	printf("%s\n",arch);
	archivo= fopen(arch,"r");
	get_token();
	if(is_id())
	{
		strcpy(NAMESPACE,  token);
		return OK;
	}
	else
		return EXPECTED_NAMESPACE_ID;
}

char* get_token()
{
	token[0]='\0';
	fscanf(archivo,"%s",token);
	return token;
}


int is_id()
{
	if(token==NULL || is_digit(token[0]))
		return FALSO;
	int i;
	for(i=0;token[i]!='\0';i++)
		if(!is_digit(token[i]) && !is_literal(token[i]) && !is_not_special_character(token[i]))
			return FALSO;
		
	return VERDADERO;
}

int body_open()
{
	int error=OK;
	get_token();
	if (strcmp(token,"{")!=FALSO)
		error=EXPECTED_BODY_OPEN;
	else{
		printf("%d body_open %s\n",cont++,token);
	}
	return error;
}

int body_close()
{
	int error=OK;
	get_token();
	if (strcmp(token,"}")!=0)
		error=EXPECTED_BODY_CLOSE;
	else{
		printf("%d body_close %s\n",cont++,token);
	}
	return error;
}

int property()
{
	int error = OK;
	char *type;
	char *ident;
	get_token();
	type=(char *) malloc(sizeof(token));
	strcpy(type,token);
	if(!is_id(type))
		error=INVALID_ID;
	else
	{
		printf("%d property type %s\n",cont++,token);
		get_token();
		ident=(char *) malloc(sizeof(token));
		strcpy(ident,token);
		if(!is_id(ident))
			error=INVALID_ID;
		else
		{
			printf("%d property id %s\n",cont++,token);
			add_property(ident,type);
		}
	}
	return error;
}

int instruction()
{
	int error=OK;
	if(strcmp(token,PROPERTY)==0)
		error=property();
	else
		error=EXPECTED_LANG_WORD;
	return error;
}

int body()
{
	int error=OK;
	error=body_open();
	while (error==OK  && (error=body_close()!=OK) && strcmp(token,"")!=0)
		error=instruction();
	return error;
}

int begin_parse()
{
	int error=OK;
	
	if(!is_id())
		error=INVALID_ID;
	else
	{
		printf("%d begin parse %s\n",cont++,token);
		add_model(token);
		body();
	}
	return error;
}
/*
int main(int nargs, char *argv[])
{
	int error=OK;
	if(nargs<2)
		error=INVALID_FILE;
	else
	{
		init(argv[1]);
		if(get_token()!=NULL && error==OK)
		{
			error=begin_parse();
		}
	}
	printf("%d\n",error);
	return error;
}*/
